package com.freightoa.sgl_login.repository

import com.freightoa.foundation.app.MMKVUtils
import com.freightoa.foundation.app.MMKVkEY
import com.freightoa.foundation.net.ApiResult
import com.freightoa.foundation.net.bean.SGLResponse
import com.freightoa.foundation.presentation.repository.BaseRepository
import com.freightoa.sgl_login.data.datasource.database.model.Data
import com.freightoa.sgl_login.data.datasource.database.model.UserType
import com.freightoa.sgl_login.net.LoginServer
import javax.inject.Inject

class LoginRepository @Inject constructor() : BaseRepository {

    @Inject
    lateinit var loginServer: LoginServer
    suspend fun login(username: String, password: String): Result<SGLResponse<Data>> {
        // 模拟登录逻辑
        return when (val apiResult = loginServer.getLogin("1", username, password)) {
            is ApiResult.Success -> {
                val data = apiResult.data.data
                MMKVUtils.putString(MMKVkEY.appKey, data?.appKey ?: "")
                MMKVUtils.putString(MMKVkEY.appToken, data?.appToken ?: "")
                MMKVUtils.putString(MMKVkEY.companyCode, data?.user?.company_code ?: "")
                MMKVUtils.putString(MMKVkEY.userId, data?.user?.user_id ?: "")
                MMKVUtils.putString(MMKVkEY.deptId, data?.user?.dept_id ?: "")
                MMKVUtils.putString(MMKVkEY.userName, data?.user?.user_name ?: "")
                MMKVUtils.putString(MMKVkEY.cfsPartyId, data?.user?.cfs_party_id ?: "")
                getUserType(apiResult.data)
            }

            is ApiResult.Error -> {
                Result.failure(RuntimeException("13"))
            }

            is ApiResult.Exception<*> -> {
                Result.failure(RuntimeException("13"))
            }
        }
    }

    private suspend fun getUserType(data: SGLResponse<Data>): Result<SGLResponse<Data>> {

        return when (val userType = loginServer.getUserType("1")) {
            is ApiResult.Success -> {
                MMKVUtils.putString(MMKVkEY.userType, userType.data.data?.user_type ?: "")
                MMKVUtils.putString(MMKVkEY.descriptionCn, userType.data.data?.description_cn ?: "")
                MMKVUtils.putString(MMKVkEY.descriptionEn, userType.data.data?.description_en ?: "")
                data.data?.userType = userType.data.data ?: UserType()
                Result.success(data)
            }

            is ApiResult.Error -> {
                Result.failure(RuntimeException("13"))
            }

            is ApiResult.Exception<*> -> {
                Result.failure(RuntimeException("13"))
            }
        }
    }

}